import os
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QSlider, QTextEdit,QHBoxLayout,QLabel,QLineEdit,QWidgetItem,QWidget
from PySide6.QtCore import Qt, QTimer,QSize
import sounddevice as sd
from scipy.io.wavfile import write
import scipy.io.wavfile as wavfile
import numpy as np
import time
from AudioPlayerWidget import AudioPlayerWidget
from httpclienttoche import HttpClientToChe
import asyncio
from PySide6.QtGui import QPixmap

import aiohttp
import PyPDF2
import docx
import qdarkstyle

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("基于BigDL-LLM的AI虚拟面试官")
        self.initUI()
        self.httpsever=HttpClientToChe()
        self.count=0
        self.questions=[]
        self.messages =[{"role": "system", "content": "欢迎使用虚拟面试官，让我们开始面试吧"}]
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        asyncio.run(self.get_all_question())
        #self.messages.append()
    
    
        
    def initUI(self):
        # 创建一个垂直布局的容器
        layout1 = QHBoxLayout()
        self.playerWidget = AudioPlayerWidget()
        
       # asyncio.run( self.playerWidget.loadAudio("audio.mp3"))  # 替换为您的音频文件路径
        self.playerWidget.show()
        vlayoutbase = QVBoxLayout()
        vlayout0 = QVBoxLayout()
        vlayout1 = QVBoxLayout()
        self.palne=QWidget()
        self.palne.setFixedSize(350, 600)
        vlayoutbase.addWidget(self.palne)
        layout1.addLayout(vlayoutbase)
        layout1.addLayout(vlayout1)
        self.palne.setLayout(vlayout0)
        # 创建录音按钮，并设置其文字根据状态变化
        self.record_button = QPushButton("开始回答")
        self.record_button.clicked.connect(self.toggle_record)
        vlayout0 .addWidget(self.record_button)
        self.start_button = QPushButton("开始面试")
        self.start_button.clicked.connect(self.start_button_clicked)
        vlayout0 .addWidget(self.start_button)
        vlayout0 .addWidget(self.record_button)
        vlayout0 .addWidget(self.playerWidget)
        image_label = QLabel()

# 使用QPixmap加载图片
        pixmap = QPixmap('girl.png')  # 替换为你的图片文件路径

# 设置图片的缩放方式，这里设置为适应QLabel的大小
        image_label.setPixmap(pixmap.scaled(QSize(350,350), Qt.AspectRatioMode .KeepAspectRatio, Qt.TransformationMode.SmoothTransformation))

# 将QLabel添加到布局管理器
        vlayout0 .addWidget(image_label)
        countlabel=QLabel("回答次数:0")
        vlayout0 .addWidget(countlabel)
      

        hlayout0 =QHBoxLayout()
        vlayout1.addLayout(hlayout0)
        label=QLabel("历史对话")
        hlayout0.addWidget(label)
        # 创建带有滑动条的文本显示框
        self.text_display = QTextEdit()
        self.text_display.setReadOnly(True)
        self.text_display.setStyleSheet("QTextEdit { background-color: rgb(0.0,0.0,156.0); color: rgb(255,255.0,255.0); font-size:16pf }")
        hlayout0 .addWidget(self.text_display)
        hlayout1 =QHBoxLayout()
        vlayout1.addLayout(hlayout1)
        # 创建文本输入框
        label1=QLabel("你的输入")
        hlayout1.addWidget( label1)
        self.text_input = QLineEdit()
        self.send_btn=QPushButton("发送")
        self.send_btn.clicked.connect(self.send_text_input)
        hlayout1.addWidget(self.text_input)
        hlayout1.addWidget( self.send_btn)
        # 设置文本输入框的高度为一行文本的高度
        self.text_input.setFixedHeight(50)
        self.text_input.textChanged.connect(self.text_input_enter)
        # 创建一个中心窗口的小部件
        central_widget = QWidget()
        central_widget.setLayout(layout1 )
        self.setCentralWidget(central_widget)
        # 创建一个状态指示器，用于更新录音按钮的文字
        self.recording = False
        # 创建一个定时器，用于模拟录音过程
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_text)

    def start_button_clicked(self):
        question=self.questions[self.count]
        self.messages.append({"role": "asstant", "content": question})
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        self.text_display .setText(message_text)   
        self.text_display .update()
        self.update()
        asyncio.run(self.send_tts(question )  )   
        pass

    async def check_finished(self,index):
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        if(self.count>9):
            all=self.text_display.toPlainText()
            next="你的面试已经结束"
            self.text_display .setText(message_text+'\n'+ next)   
            self.text_display .update()
            await self.send_tts( next)
            pass
  
       

    def send_text_input(self):   
        content=self.text_input.text()
        self.messages.append({"role": "user", "content": content})
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        self.text_display .setText(message_text)   
        self.text_display .update()
        self.update()
    
        asyncio.run(self.get_grade_and_shownext(content))
        pass 

    async def get_grade_and_shownext(self,content):
        await self.send_content_get_grade(content)
        await self.check_finished(self.count)
        pass

    def text_input_enter(self):    
        pass    
    def toggle_record(self):
        self.recording = not self.recording
        if self.recording:
            self.record_button.setText("停止")
            self.recordasynv()    
        else:
            self.record_button.setText("录音")
            self.timer.stop()
            sd.stop()
            fs = 44100  # 采样率
            wavfile.write('record_output.wav', fs, self.audio_data)
            #发送和识别语音
            content1=self.httpsever.post_audio_transcription('record_output.wav')
            content=content1.get('text')[0]
            #content=first_choice.get('text')
            self.messages.append({"role": "user", "content": content})
            print('transcription:'+content)
            message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
            self.text_display .setText(message_text)   
            self.text_display .update()
            sendmessages=self.messages
            asyncio.run(self.get_grade_and_shownext(content))
            #获取新的问题和评价
           


    async def send_content_get_grade(self,content):
       
        rescentent=self.httpsever.get_bigdl_fenshu(content,self.count) 
        self.count=self.count+1
        self.messages.append({"role": "asstant", "content": rescentent})
        #self.text_display.setText(rescentent)  
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        self.text_display .setText(message_text)   
        self.text_input.setText(" ")
        self.audio_data = None
        self.update_text()
        if(self.count>9):
            self.send_tts(rescentent) 
            return 0
        question=self.questions[self.count]
        self.messages.append({"role": "asstant", "content": question})
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        self.text_display .setText(message_text)   
        self.text_display .update()
        self.update()
        await  self.send_tts(rescentent+question )        
       
        pass
    def recordasynv(self):
        self.timer.start(1000)  # 每秒更新一次文本
            # 设置录音参数
        duration = 30  # 录音时间（秒）
        fs = 44100  # 采样率
        self.audio_data = sd.rec(duration*fs, samplerate=fs, channels=2, dtype='int16')
        #sd.wait()  # 等待录音完成
        print("录音结束。")
        pass

    #发送文字并且播放tts音频
    async def send_tts(self,content):
        self.playerWidget.stop()
        print(content)
        filepath=await self.generate_voice(content)
        self.playerWidget.loadAudio(filepath)
        await self.playerWidget.play()       
        pass
    
    async def get_all_question(self):
        self.questions=self.httpsever.get_mianshi_allquestion()
        pass

    async def generate_voice(self,content):
        filepath=self.httpsever.generate_voice(content)
        return filepath

    def update_text(self):
        if self.recording:
            text = "正在录音...\n" + self.text_display.toPlainText()
        else:
            text = self.text_display.toPlainText()
        self.text_display.setPlainText(text)

 

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyside6'))
    window = MainWindow()
    window.show()
    sys.exit(app.exec())